var CONFIG = {
    "downloadFileUrl": "/download/file.html",
    "imgUrl": "http://baopaistatic.xj-mall.com.cn",
    //"imgUrl":"http://172.16.2.203:8010",
    "siteUrl": '',//"http://192.168.0.73/",
    "apiUrl": "http://baopai.xj-mall.com.cn/api",
    // "apiUrl":"http://172.16.100.33:8083/bp_module_web",
    "pageSize": 10,
};
/**
 * cookie pligin for jQuery
 *
 * @version 1.0.0
 *
 * options expires: 定义cookie的有效时间，默认'' s是指秒， 如20秒就是20s h是指小时，如12小时是h12
 * d是指天数，如30天就是d30 path: 定义cookie的有效路径,默认为'' domain: 定义cookie的domain secure:
 * 默认值：false。如果为true，cookie的传输需要使用安全协议（HTTPS） raw: 默认情况下，读取和写入 cookie
 * 的时候自动进行编码和解码.要关闭这个功能设置 raw: true 即可
 *
 */
(function ($) {

    $.cookie = function (key, value, options) {
        var opts;
        // 设置cookie
        var val = String(value);
        if (arguments.length > 1 && val !== "[object Object]") {
            var time, num, type, strsec = 0,
                exp = new Date();
            opts = $.extend({}, $.cookie.defaults, options);
            /*
             * time = { null: "d-1", undefined: "d-1" }[value] || opts.expires;
             * console.log("time-->"+time.length);
             */
            /*
             * time != '' && (num = time.substring(1, time.length) * 1, type =
             * time.substring(0, 1), strsec = { 's': num * 1000, 'h': num * 60 *
             * 60 * 1000, 'd': num * 24 * 60 * 60 * 1000 }[type],
             * exp.setTime(exp.getTime() + strsec * 1), time = ";expires=" +
             * exp.toGMTString());
             */
            return (document.cookie = [
                encodeURIComponent(key), '=',
                opts.raw ? val : encodeURIComponent(val),
                time,
                opts.path ? '; path=' + opts.path : '/',
                opts.domain ? '; domain=' + opts.domain : '',
                opts.secure ? '; secure' : ''
            ].join(''))
        }
        // 获取cookie
        opts = $.extend({}, $.cookie.defaults, value);
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? {
            true: result[1],
            false: decodeURIComponent(result[1])
        }[opts.raw] : null
    };

    $.cookie.defaults = {
        expires: '',
        path: '/',
        secure: false,
        raw: false,
        domain: ''
    };
})(jQuery)

    ;
(function ($) {

    // 绑定通用事件
    $('body').on('tap', '#reload', function () {
        return window.location.reload();
    });

    // 绑定通用事件
    $('body').on('tap', '#scBack', function () {
        // return $.gotoUrl('securityCenter.html');
        return $.gotoUrl('index');
    });

    $('body').on('tap', '#goToLogin', function () {
        // return $.gotoUrl('securityCenter.html');
        return $.gotoUrl('system/login.html');
    });

    // 基本配置项
    $.baseConfig = function () {
        var baseConfig = {
            // 数据加载失败模板
            noDataTemplate: '<div class="no-data"><div></div><p>数据加载失败，请稍后再试</p><button id="reload" class="btnBig-nb ui-mt35 mb20">重新加载</button></div>'
        };
        return function () {
            return baseConfig;
        };
    }();

    /** *cookie 公用 */
    $.setSession = function (name, value, option) {
        if (typeof value != "string") {
            value = $.toJSON(value);
        }
        option = option || {
            path: "/",
            expires: 30
        };

        return $.cookie(name, value, option);
    };

    $.getSession = function (name) {
        var value = $.cookie(name);
        if (value && value.indexOf("{") != -1) {
            value = $.evalJSON(value);
        }
        if (!value || value == "false" || value == undefined || value == "") {
            value = null;
        }
        return value;
    };

    $.deleteSession = function (name) {
        var name = decodeURIComponent(name);
        $.cookie(name, null, {
            expires: -1,
            path: '/'
        });
    };

    $.delAllSession = function (excludeArr) {
        // js 遍历所有Cookie
        var strCookie = document.cookie;
        var arrCookie = strCookie.split("; "); // 将多cookie切割为多个名/值对
        for (var i = 0; i < arrCookie.length; i++) { // 遍历cookie数组，处理每个cookie对
            var arr = arrCookie[i].split("=");
            var status;
            if (arr.length > 0) {
                status = true;
            }
            if (excludeArr && excludeArr.length > 0) {
                for (var exclude in excludeArr) {
                    if (excludeArr[exclude] == arr[0]) {
                        status = false;
                        break;
                    }
                }
            }
            if (status) {
                $.deleteSession(arr[0]);
            }
        }
    };

    /** ***LocalStrong** */

})(jQuery);

/**
 * 从url中获取参数
 */
;
(function ($) {
    $.getRequestData = function (url) {
        if (url) {
            if (url.indexOf("?") == -1) {
                return {};
            } else {
                url = '?' + url.split('?').pop();
            }
        } else {
            // 获取url中"?"符后的字串
            url = location.search;
        }
        var theRequest = {};
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    };

    $.createUrl = function (obj) {
        var length = obj && obj.length,
            idx = 0,
            url = obj.url + '?';
        for (var key in obj) {
            if (key != 'url' && obj[key] !== null) {
                url += (key + '=' + encodeURIComponent(obj[key]) + '&');
            }
        }
        return url.substring(0, url.lastIndexOf('&'));
    };

    $.ellipsis = function (str, len) {
        if (str.length > len) {
            str = str.substring(0, len) + "...";
        }
        return str;
    };

    $.getRandom = function () {
        var time = new Date().getTime();
        time = time + "" + parseInt(Math.random() * 100);
        return time;
    };
})(jQuery)

    /**
     * 判断div是否显示
     */
    ;
(function ($) {


    $.fn.isHide = function () {
        return isHide(this);
    };

    $.fn.isShow = function () {
        return !isHide(this);
    };

    function isHide(target) {
        if (target.length === 1) {
            if (target[0].style.display === 'none') {
                return true;
            }
            return false;
        }
    }

})(jQuery)


    /**
     * json转对象
     *
     */
    ;
(function ($) {
    $.paseJson = function (o) {
        if ($.isNumber(o)) {
            return o;
        }
        var result;
        try {
            result = JSON.parse(o);
            if (typeof (result) !== 'object') {
                return o;
            }
        } catch (e) {
            result = o;
        }
        return result;
    }

    $.isNumber = function (string) {
        return /^[0-9]*$/.test(string);
    }
})(jQuery)


    /**
     * 页面非空校验
     *
     */
    ;
(function ($) {
    $.pageEmptyCheck = function (o) {
        $.each(o, function (index, item) {
            $("#" + item).isEmpty();
        })
    }
})(jQuery)


    /**
     * HTML5 LocalStorage 本地存储
     *
     * save $.ls("sample","123") get $.ls("sample") delete $.ls("sample",null) *
     *
     * _prefix 批量删除前缀，不传则删除全部
     */
    ;
(function ($) {
    $.ls = function (key, value) {

        var ls = window.localStorage || window.sessionStorage;

        if (arguments.length > 1) {
            return value == null ? ls.removeItem(key) : typeof (value) != "object" ? save(key, value) : save(key, JSON.stringify(value));
        }

        return $.paseJson(ls.getItem(key));

        function save(key, value) {
            ls.setItem(key, value);
        }
    };

    $.ls_del_prefix = function (_prefix) {
        var ls = window.localStorage || window.sessionStorage;
        if (_prefix == undefined || _prefix == null) {
            ls.clear();
            return;
        }
        var leng = ls.length;
        for (var i = 0; i < leng; i++) {
            var key = ls.key(i);
            if (key && key.indexOf(_prefix) == 0) {
                ls.removeItem(ls.key(i));
            }
        }
    }

})(jQuery)


    /**
     * 将数值四舍五入(保留2位小数)后格式化成金额形式
     *
     * @param num
     *            数值(Number或者String)
     * @param type
     *            数值(1:四舍五入，2：去尾法，3：增一法)
     * @return 金额格式的字符串,如'1,234,567.45'
     * @type String
     */
    ;
(function ($) {
    $.formatCurrency = function (num, type) {
        if (!type) {
            type = 1;
        }
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = num * 100;
        num = type === 1 ? Math.round(num) : type === 2 ? Math.floor(num) : Math.ceil(num);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
                num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '-') + num + '.' + cents);
    };

    /**
     * 货币格式化 scale：小数位 sign：boolean 人民币标识 unit：boolean 是否加元
     */
    $.currency = function (value, scale, sign, unit, eng) {
        scale = scale || 2;
        var price = $.formatCurrency(value);
        if (sign) {
            price = "￥" + price;
        }
        if (unit) {
            price += "元";
        }
        if (eng) {
            price = "$" + price;
        }
        return price;
    }
})(jQuery)

    /**
     *
     * main
     */
    ;
(function ($) {

    $.fn.securityTap = function (ops) {
        if (!ops) {
            return $.alert("系统维护中，请稍后再试");
        }
        var _this = $(this);
        if (_this.attr('disabled')) {
            return false;
        }
        _this.attr('disabled', 'disabled');

        if (ops.isIllegal && ops.isIllegal()) {
            return;
        }
        var error;

        if (typeof (ops.checkPara) === 'function') {
            error = ops.checkPara();
        } else {
            error = ops.checkPara && $.verifyPara(ops.checkPara);
        }
        if (error) {
            return _this.removeAttr('disabled');
        }
        $.commonAjax({
            url: ops.ajax.url,
            type: ops.ajax.type,
            data: ops.ajax.data,
            success: function (data) {
                ops.success && ops.success(data);
                ops.isNotJump && _this.removeAttr('disabled');
            },
            error: function (error) {
                ops.error && ops.error(error);
                _this.removeAttr('disabled');
            }
        });
    };


    $("#backBtn").on("tap", function () {
        window.history.go(-1);
    });

    /**
     * 页面版本控制 页面code获取当前页面版本信息
     */
    $.redirect = function (option) {
        // index暂时走框架机，所以不要加.html
        if (option === 'index') {
            return option;
        }

        return option + '.html';
    };

    /*
     * 国内手机号校验
     */
    $.fn.isPhoneNo = function () {
        // 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
        // 联通：130、131、132、152、155、156、185、186
        // 电信：133、153、180、189、（1349卫通
        var err;
        var mobile = this.val();
        if (!mobile) {
            err = "请输入手机号码";
        }
        err = err && err || (!(/^1\d{10}$/.test(this.val())) ? "请输入正确格式手机号码" : undefined);

        err && $.alert(err);
        return !err;
    };

    $.fn.isEmpty = function () {
        var _this = this;
        var value = $(_this).val();
        var err = value ? undefined : ("请输入" + _this[0].name);
        err && $.alert(err);
        return err;
    };

    $.verifyPara = function (options) {
        for (var i = 0; i < options.length; i++) {
            if (typeof (options[i][1]) === 'function' && options[i][1]()) {
                return $.alert(options[i][0]);
            }
            if (!options[i][1]) {
                return $.alert("请输入" + options[i][0]);
            }
        }
    };


    // checkBos ischecked(true:checked;false:none)
    $.fn.isChecked = function (isChecked) {
        isChecked && this.attr("checked", "checked") || this.removeAttr("checked");
    };

    $.len = function (str) {
        if (str == null) return 0;
        if (typeof str != "string") {
            str += "";
        }
        return str.replace(/[^\x00-\xff]/g, "01").length;
    }
    // 动态加载script
    $.load_script = function (xyUrl, callback) {
        var head = doc.getElementsByTagName('head')[0];
        var script = doc.createElement('script');
        script.type = 'text/javascript';
        script.src = xyUrl;
        // 借鉴了jQuery的script跨域方法
        script.onload = script.onreadystatechange = function () {
            if ((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                callback && callback();
                // Handle memory leak in IE
                script.onload = script.onreadystatechange = null;
                if (head && script.parentNode) {
                    head.removeChild(script);
                }
            }
        };
        // Use insertBefore instead of appendChild to circumvent an IE6 bug.
        head.insertBefore(script, head.firstChild);
    };

    // 随机生成函数名
    $.createFunctionName = function () {
        return 'cbk_' + Math.round(Math.random() * 10000); // 随机函数名
    };


    // ----------------------------------------------------------------------
    // <summary>
    // 限制只能输入数字和字母
    // </summary>
    // ----------------------------------------------------------------------
    $.onlyNumAlpha = function (obj) {
        $(obj).keypress(function (event) {
            var eventObj = event || e;
            var keyCode = eventObj.keyCode || eventObj.which;
            if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122))
                return true;
            else
                return false;
        }).focus(function () {
            obj.style.imeMode = 'disabled';
        }).bind("paste", function () {
            var clipboard = window.clipboardData.getData("Text");
            if (/^(\d|[a-zA-Z])+$/.test(clipboard))
                return true;
            else
                return false;
        });
    };

    //两位小数
    $.onlyTwoInt = function (obj) {
        obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
        obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
        obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    }

})(jQuery)

    /**
     * ajax调用 ops : type (默认： “GET”)：请求方法 (“GET”, “POST”, or other) url (默认：
     * 当前地址)：发送请求的地址 data (默认：none)：发送到服务器的数据；如果是get请求，它会自动被作为参数拼接到url上。非String对象将通过
     * $.param 得到序列化字符串。 processData (默认： true)： 对于非Get请求。是否自动将 data 转换为字符串。
     * contentType (默认： “application/x-www-form-urlencoded”)： 发送信息至服务器时内容编码类型。
     * (这也可以通过设置headers headers)。通过设置 false 跳过设置默认值。 dataType (默认：
     * none)：预期服务器返回的数据类型(“json”, “jsonp”, “xml”, “html”, or “text”) timeout (默认：
     * 0)： 设置请求超时时间（毫秒），0表示不超时。 headers (默认：{})： 一个额外的"{键:值}"对映射到请求一起发送 async (默认：
     * true)：默认设置下，所有请求均为异步。如果需发送同步请求，请将此设置为 false。 global (默认：
     * true)：请求将触发全局AJAX事件处理程序，设置为 false 将不会触发全局 AJAX 事件。 context (默认： window)：
     * 这个对象用于设置Ajax相关回调函数的上下文(this指向)。 traditional
     * (默认：false)：激活传统的方式通过$.param来得到序列化的 data。
     */
    ;
(function ($) {

    var page = {
        lastPageNumber: 0,
        firstRecordTime: 0,
        lastRecordTime: 0
    },
        rt,
        lock = {};

    $.commonAjax = function (options) {
        options.host = CONFIG.apiUrl;

        if (lock[options.url]) {
            return false;
        }
        lock[options.url] = 1;

        // 接口定义
        var Url = {
            // 首页接口
            B001: "/xxxxx/list.html",// 首页轮播广告位接口,advert会被插件拦截
            B002: "/album/list.html",// 专场列表
            B003: "/index/today.html",// 今日竞拍
            B004: "/index/publicity.html",// 公示期列表
            B005: "/index/news.html",// 竞拍新闻
            B006: "/index/list.html",// 首页商品列表
            // 登录/注册/找回密码接口
            B007: "/member/login.html",// 用户登录接口
            B008: "/member/register.html",// 注册接口
            B009: "/member/find_passwd_1.html",// 找回密码第一步
            B010: "/member/find_passwd_2.html",// 找回密码第二步
            B011: "/member/find_passwd_3.html",// 找回密码第三步
            // 公用接口
            B012: "/common/category_list.html",// 分类查询接口
            B013: "/common/area_list.html",// 地区查询接口
            B014: "/common/msend_sms.html",// 短信发送
            B015: "/common/code_image.html",// 图片验证码访问地址
            B016: "/upload/documentByTrans.html",// 竞拍成交合同上传

            // 商品委托流程接口
            B017: "/goods/entrust.html",// 委托第一步接口
            //文件上传接口      
            B018: "/upload/document.html",//文件上传
            B019: "/upload/image.html",//商品图片上传，裁剪压缩
            B020: "/upload/individual.html",//文件上传，仅返回文件访问地址

            // 商品接口
            B021: "/auction/page.html",// 商品查询接口
            B022: "/album/detail.html",// 专场详情
            B023: "/album/goods/list.html",// 专场拍品分页列表
            B024: "/auction/{auctionCode}.html",// 拍品详情接口
            B025: "/auction/addCollection.html",// 添加收藏接口
            B026: "/auction/bids.html",// 出价记录查询
            //商品委托流程
            B027: "/auction/entrust_template.html", //竞拍协议模板
            B028: "/auction/submit_contract.html", //上传委托拍卖协议
            B029: "/goods/edit.html",  //拍品属性修改接口
            B030: "/upload/imageByH5.html",//商品H5方式图片上传，裁剪压缩
            B031: "/common/system_time.html",//获取系统时间
            B032: "/upload/documentByH5.html",//文件H5方式上传
            B033: "/goods/add_images.html",//拍品图片添加
            B034: "/goods/delete_images.html",//拍品图片删除
            B035: "/auction/detail.html",//竞拍详情查询接口
            B036: "/goods/images_list.html",//拍品图片列表
            B037: "/goods/detail.html",//拍品详情查询
            B038: "/goods/document_list.html",//拍品文档列表
            B039: "/individual/info.html",//个人信息接口
            B040: "/common/send_mail.html",//发送邮件
            B041: "/individual/bind_email.html",//绑定邮箱
            B042: "/individual/bind_phone.html",//绑定手机号
            B043: "/individual/personal_auth.html",//身份证认证
            B044: "/individual/enterprise_auth.html",//企业认证
            B045: "/individual/personal.html",//身份认证详情
            B046: "/individual/enterprise.html",//企业认证详情
            B047: "/individual/effectiveCredentials.html",//经营资质列表
            B048: "/individual/editCredentials.html",//保存经营资质
            B049: "/myentrust/manage.html",//拍品管理
            B050: "/auction/delCollection.html",//取消关注拍品
            B051: "/auction/detail_template.html",//拍品详情文档
            B052: "/auction/page/browse.html",//用户浏览记录查询分页接口
            B053: "/auction/addCollection.html",//拍品收藏接口
            B054: "/auction/page/collections.html",//用户收藏查询分页接口
            B055: "/member/update_passwd.html",//修改密码接口
            B056: "/order/createOrder.html",//创建订单(缴纳保证金)
            B057: "/common/pay_channel_list.html",//可用支付渠道接口
            B058: "/auction/page.html",//竞拍列表查询
            B059: "/order/pay_offline.html",//汇款支付
            B060: "/myentrust/bids.html",//我的竞拍接口
            B061: "/myentrust/trans.html",//买家成交
            B062: "/myentrust/trans_book.html",//上传成交确认书
            B063: "/myentrust/trans_contact.html",//上传成交确认合同  
            B064: "/auction/realtime.html",//拍品实时信息
            B065: "/myentrust/qualification/page.html",//(我的拍卖)保证金接口
            B066: "/myentrust/qualification/detail.html",//保证金详情接口
            B067: "/order/detail.html",//订单信息查询
            B068: "/auction/bid.html",// 竞拍出价
            B069: "/auction/submit_detail_contract.html",//拍品详情文档提交
            B070: "/goods/applyAudit.html", //提交审核
            B071: "/album/auctionList.html",//专场拍品列表
            B072: "/album/detail.html",//专场详情
            B073: "/common/is_login.html",//校验token是否可用
            B074: "/webmarket/standard_list.html",//行情分析规格查询
            B075: "/webmarket/standardArea_list.html",//行情分析规格地区查询
            B076: "/webmarket/market_week.html",//一周行情查询
            B077: "/webmarket/market_month.html",//一个月行情查询
            B078: "/webmarket/market_three_month.html",//三个月行情查询
            B079: "/webmarket/market_half_year.html",//半年行情查询
            B080: "/common/category_listAll.html",//行情中心分类查询
            B081: "/download/file.html",//下载文件
            B082: "/common/category_all.html",//行情商品种类集合
            B083: "/auction/recommend_week.html",//相关推荐一个星期
            B084: "/auction/recommend_month.html",//相关推荐一个月
            B085: "/auction/recommend_three_month.html",//相关推荐三个月
            B086: "/auction/recommend_half_year.html",//相关推荐半年
            B087: "/goods/lose.api",
            B088: "/article/list",//行业新闻,公告列表
            B089: "/article/getArticle",//行业新闻，公告列表详情    
            B090: "/order/payVIP",//vip账户保证金免支付
            B091: "/webmarket/defaultCategoryCode",//行情页面初始化默认数据
            B092: "/question/add.api",//用户留言POST

            //13 感兴趣分类
            B093: "/follow/add.api",//添加感兴趣分类post
            B094: "/follow/delete.api",//删除感兴趣分类post
            B095: "/follow/list.api",//用户感兴趣分类列表post
            B096: "/follow/auctionList.api",//感兴趣上商品列表
            B097: "/order/payAllinpay.api",//通联在线支付
            B098: "/goods/video_list.api",//获取商品视频文件列表
			
			B099:"/upload/imageByH5Org.html" //图片上传(不压缩);
        };
        var headers = $.extend({}, $.commonAjax.headers, options.headers);
        var ops = $.extend({}, $.commonAjax.defaults, options);
        ops.headers = headers;
        dataJson = ops.data;
        headers.checkcode = $.ls("bp_checkcode");//ls 设置问题

        /*if (ops.type.toUpperCase() != "GET") { dataJson =
       JSON.stringify(ops.data); }*/

        if (dataJson.pageNumber && dataJson.pageSize) {
            if (dataJson.pageNumber > 1) {
                dataJson.lastPageNumber = page.lastPageNumber;
                dataJson.firstRecordTime = page.firstRecordTime;
                dataJson.lastRecordTime = page.lastRecordTime;
            } else {
                dataJson.lastPageNumber = 0;
                dataJson.firstRecordTime = 0;
                dataJson.lastRecordTime = 0;
            }

        }
        var url = Url[ops.url] ? Url[ops.url] : ops.url;
        if (ops.type.toUpperCase() == "DELETE") {// 删除操作
            url = url + "/" + ops.data.nextObj + '/' + ops.data.status;
            ops.data.nextObj = null;
            ops.data.status = null;
        }
        if (ops.showLoad == undefined || ops.showLoad == null) {
            ops.showLoad = true;
        }
        return $.ajax({
            type: ops.type ? ops.type : 'GET',
            url: (ops.host + url),
            data: dataJson,
            dataType: 'json',
            headers: ops.headers,
            timeout: 15000,
            async: ops.async,
            crossDomain: true,
            beforeSend: function () {
                if (ops.showLoad == true) {
                    if (layer) {
                        layer.closeAll('loading');
                    }
                    //$.layerload();
                }
            },
            // contentType: 'application/json',
            success: function (data) {
                if (ops.showLoad == true) {
                    if (layer) {
                        layer.closeAll('loading');
                    }
                }
                // 记录最晚活动时间
                countDown = new Date();
                lock[options.url] = 0;
                if (data && data.page) {
                    page = {
                        lastPageNumber: data.page.lastPageNumber,
                        firstRecordTime: data.page.firstRecordTime,
                        lastRecordTime: data.page.lastRecordTime
                    };
                }
                if (data.code == '401') {// 登录超时
                    $.ls("bp_login_out_url", window.location.href);
                    $.ls("bp_token", null);
                    $.ls("bp_userName", null);
                    $.ls("bp_memberInfo", null);
                    $.ls("bp_memberCode", null);
                    if (data.msg && data.msg.length > 0) {
                        $.defaultDialog(data.msg, 2000, function () {
                            window.location.href = CONFIG.siteUrl + "signIn.html";
                        });
                    }
                    return false;
                }
                ops.success && ops.success(data);
            },
            error: function (data) {
                if (ops.showLoad == true) {
                    if (layer) {
                        layer.closeAll('loading');
                    }
                }
                lock[options.url] = 0;
                if (data.code == '401') {// 登录超时
                    $.ls("bp_login_out_url", window.location.href);
                    $.ls("bp_token", null);
                    $.ls("bp_userName", null);
                    $.ls("bp_memberInfo", null);
                    $.ls("bp_memberCode", null);
                    if (obj.msg && obj.msg.length > 0) {
                        $.defaultDialog(obj.msg, 2000, function () {
                            window.location.href = CONFIG.siteUrl + "login.html";
                        });
                    }
                    return false;
                } else if (data.responseJSON && data.responseJSON.code == "9999" && data.responseJSON.msg) {
                    $.layermsg(data.responseJSON.msg);
                    return false;
                }
            }
        });
    };
    $.commonAjax.defaults = {
        host: CONFIG.apiUrl,
        type: 'GET',
        url: null,
        data: {},
        openDialog: true,
        processData: true,
        // contentType: 'application/json',
        // dataType: 'json',
        // crossDomain: true,
        timeout: 3000,
        defaultErrorMsg: '获取信息失败',
        async: true,
        global: true,
        context: window,
        traditional: false
    };

    $.commonAjax.headers = {
        'token': $.ls("bp_token") ? $.ls("bp_token") : "",
        'memberCode': $.ls("bp_memberCode") ? $.getSession("bp_memberCode") : "",
        'checkcode': $.ls("bp_checkcode") ? $.ls("bp_checkcode") : ""
    };

})(jQuery)

    /**
     * Created by bruce on 2015/4/14.
     */
    ;
(function ($) {
    /***************************************************************************
     * type:0全部；1 日期类型；2时间类型
     */
    $.dateFormat = function (time, type) {
        var datetime = new Date();
        datetime.setTime(time);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        if (type && type == "1")
            return year + "-" + month + "-" + date;
        else if (type && type == "2")
            return hour + ":" + minute + ":" + second;
        else
            return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    };

    // 校验手机号
    $.v_mobile = function (val) {
        var p = /^1\d{10}$/;
        if (p.test(val)) {
            return true;
        }
        return false;
    };

})(jQuery)

    // 边框闪烁
    ;
(function ($) {
    $.twinkle = function (domid) {
        if (domid) {
            var dom = $("#" + domid);
            if (dom.length > 0) {
                location.href = "#" + domid;
                var interval = setInterval(function (dom) {
                    if (dom.hasClass('twinkle')) {
                        dom.removeClass('twinkle');
                    } else {
                        dom.addClass('twinkle');
                    }
                }, 50, dom);
                setTimeout(function (data) {
                    clearInterval(data[0]);
                    dom.removeClass('twinkle');
                }, 500, [interval, dom]);
            }
        }


    }
})(jQuery)



    /**
     * 弹出框框
     *
     */
    ;
(function ($, window, undefined) {

    /**
     * 基本提示框信息
     */
    $.defaultDialog = function (msg, time, colseCallBack) {
        var time = time || 2000;
        layer.msg(msg, {
            shade: [0.1, '#fff'],
            // area: ['250px','50px'],
            time: time // 2秒关闭（如果不配置，默认是3秒）
        }, function () {
            if (colseCallBack)
                colseCallBack();
        });
    };

    $.alert = function (msg) {
        $.defaultDialog(msg);
    }

    $.layermsg = function (msg) {
        layer.msg(msg);
    };

    $.layerload = function () {
        var loadlayer = layer.load();
        return loadlayer;
    };

})(window.jQuery, window);

var timer;
var BASE = {
    init: function () {

        /* 演示清除input */
        $('body').on('tap', '.c-close-btn', function () {
            $(this).siblings('input').val("");
            // $(this).parent().find("input").val("");
        });

        /* 出现删除× */
        $('body').on('focus', '.c-input input', function () {
            $(this).siblings('.c-close-btn').show().css("display", "inline-block");
            // var index = $(".c-close-btn").parent().find("input").index(this);
            // $(".c-close-btn").parent().find("input").eq(index).next().show().css("display",
            // "inline-block");
        })
        $('body').on('blur', '.c-input input', function () {
            $(this).siblings('.c-close-btn').hide();
            // var index = $(".c-close-btn").parent().find("input").index(this);
            // $(".c-close-btn").parent().find("input").eq(index).next().show().css("display",
            // "inline-block");
        })

        /* 演示清除input（新的） */
        $('body').on('tap', '.ui-icon-clear', function () {
            $(this).siblings('input').val("");
            $(this).siblings('input').focus();
        });

        /* 出现删除× */
        $('body').on('focus', '.ui-input-nbd input', function () {
            if ($(this).val().length > 0) {
                $(this).siblings('.ui-icon-clear').show().css("display", "inline-block");
            }
            else {
                $(this).siblings('.ui-icon-clear').hide();
            }
            $(this).closest('.ui-input-nbd').addClass('current');
        })
        $('body').on('keyup', '.ui-input-nbd input', function () {
            if ($(this).val().length > 0) {
                $(this).siblings('.ui-icon-clear').show().css("display", "inline-block");
            }
            else {
                $(this).siblings('.ui-icon-clear').hide();
            }
        })
        $('body').on('blur', '.ui-input-nbd input', function () {
            $(this).siblings('.ui-icon-clear').hide();
            $(this).closest('.ui-input-nbd').removeClass('current');
        })


        this.headerNav();
        /*
         * if (!CONFIG.debug) { try { template.onerror = function(err) {
         * $.location("500.html"); } } catch (e) {} }
         */
        /*
         * $(document).on('scroll', function(){ var scrollElement =
         * document.getElementById('goTop'); if(scrollElement){
         * scrollElement.style.display = (document.documentElement.scrollTop +
         * document.body.scrollTop) ? 'block' : 'none'; } })
         *
         * $('#goTop').on('tap', function(){ BASE.goTop(); return false; })
         */
    },
    headerNav: function () {
        if ($("#mainPage").size() > 0) {
            $("#mainPage").on("tap", function () {
                $.gotoUrl($.redirect("index"));
            })
        }
        if ($("header .arrow").size() > 0) {
            $("header .arrow").on("tap", function () {
                $.backUrl();
            })
        }
    },
    /*
     * 1428914190125 -> 2015-12-21 12:21:32
     */
    strToTime: function (time) {
        time = new Date(parseInt(time, 10));
        return time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " " + (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) + ":" + (time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes()) + ":" + (time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds());
    },
    /*
     * 1428914190125 -> 2015-12-21 12:21
     */
    strToTime2: function (time) {
        time = new Date(parseInt(time, 10));
        return time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " " + time.getHours() + ":" + (time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes());
    },
    /*
     * 1428914190125 -> 2015-12-21
     */
    strToDate: function (time) {
        time = new Date(parseInt(time, 10));
        return time.getFullYear() + "-" + ((time.getMonth() + 1) < 10 ? "0" + (time.getMonth() + 1) : (time.getMonth() + 1)) + "-" + (time.getDate() < 10 ? "0" + time.getDate() : time.getDate());
    },
    /*
     * 计算剩余时间
     */
    calRestTime: function (endTime, nowTime) {
        if (nowTime) {
            leftTime = endTime - nowTime;
        } else {
            var nowTime = new Date();
            leftTime = endTime - nowTime.getTime();
        }
        if (leftTime < 0) {
            return '已过期';
        }
        var leftSecond = parseInt(leftTime / 1000);
        var day = Math.floor(leftSecond / (60 * 60 * 24));
        var hour = Math.floor((leftSecond - day * 24 * 60 * 60) / 3600);
        var minute = Math.floor((leftSecond - day * 24 * 60 * 60 - hour * 3600) / 60);
        var second = Math.floor(leftSecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
        if (day == 0) {
            return hour + "小时" + minute + "分" + second + "秒";
        }
        return day + "天" + hour + "小时" + minute + "分" + second + "秒";
    },

    jsonToQuery: function (json, replacer_opt) {
        var result = [],
            itemLen,
            replacer = replacer_opt || function (value) {
                return BASE.escapeSymbol(value);
            };
        for (key in json) {
            result.push(key + '=' + replacer(json[key], key));
        }
        return result.join('&');
    },
    queryToJson: function (url) {
        var query = url.substr(url.lastIndexOf('?') + 1).split('#')[0],
            params = query.split('&'),
            len = params.length,
            result = {},
            i = 0,
            key, value, item, param;
        for (; i < len; i++) {
            if (!params[i]) {
                continue;
            }
            param = params[i].split('=');
            key = param[0];
            value = param[1];
            item = result[key];
            if ('undefined' == typeof item) {
                result[key] = value;
            } else {
                result[key] = [item, value];
            }
        }
        return result;
    },
    getUrlParams: function () {
        try {
            var href = window['location']['href'];
            var sParam = href.substring(href.indexOf('?')).split('#')[0];
            var params = BASE.queryToJson(sParam);

            for (var p in params) {
                try {
                    params[p] = decodeURIComponent(params[p]);
                } catch (e1) {
                }
            }
            return params;
        } catch (e) {
            return {};
        }
    },
    // JavaScript Document
    goTop: function (acceleration, time) {
        acceleration = acceleration || 0.1;
        time = time || 8;
        var x1 = 0;
        var y1 = 0;
        var x2 = 0;
        var y2 = 0;
        var x3 = 0;
        var y3 = 0;

        if (document.documentElement) {
            x1 = document.documentElement.scrollLeft || 0;
            y1 = document.documentElement.scrollTop || 0;
        }
        if (document.body) {
            x2 = document.body.scrollLeft || 0;
            y2 = document.body.scrollTop || 0;
        }
        var x3 = window.scrollX || 0;
        var y3 = window.scrollY || 0;

        // 滚动条到页面顶部的水平距离
        var x = Math.max(x1, Math.max(x2, x3));
        // 滚动条到页面顶部的垂直距离
        var y = Math.max(y1, Math.max(y2, y3));

        // 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小
        var speed = 1 + acceleration;
        window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));

        // 如果距离不为零, 继续调用迭代本函数
        if (x > 0 || y > 0) {
            var invokeFunction = "BASE.goTop(" + acceleration + ", " + time + ")";
            window.setTimeout(invokeFunction, time);
        }
    },

};


BASE.init();


window.Boss = {};


/**
 * 下拉选择框
 *
 */
;
(function ($, window, undefined) {

    var SelectModule = function (options) {

        this.settings = $.extend({}, SelectModule.defaults, options);

        this.init();

    };

    SelectModule.prototype = {

        /**
         * 初始化
         */
        init: function () {

            this.create();

        },

        /**
         * 创建
         */
        create: function () {


            var title = this.settings.title,
                context = '',
                selectList = this.settings.content,
                domList = [];

            var dom = [
                '<div id="selectModule" style="" class="dialog-box-end">',
                '    <div class="select-popup dialog-end">',
                '        <div class="title-line boxpack-center">',
                '            <p id="cancel" class="select-cancel">×</p>',
                '            <h3 class=" boxflex-one">',
                title,
                '</h3>',
                '            <p id="ok" class="select-ok"><i></i></p>',
                '        </div>',
                '        <div id="animation-effect" class="choose-area iSlider-effect">',
                '        <div class="current-line"></div>',
                '        </div>',
                '    </div>',
                '</div>'
            ].join('');
            // 追回到body
            $('body').append(dom);

            for (var i = 0; i < selectList.length; i++) {
                context = {
                    content: '<p id=' + selectList[i].key + '>' + selectList[i].value + '</p>'
                };
                domList.push(context);
            }

            var islider1 = new iSlider({
                data: domList,
                dom: document.getElementById("animation-effect"),
                type: 'dom',
                animateType: 'depth-h',
                isLooping: true,
                isVertical: true
            });

            // 设置cancel按钮
            if ($.isFunction(this.settings.cancel)) {
                this.cancel();
            }

            // 设置ok按钮
            if ($.isFunction(this.settings.ok)) {
                this.ok();
            }


            // 设置大小
            this.size();

            // 设置位置
            this.position();

        },


        /**
         * cancel
         */
        cancel: function () {

            var _this = this;

            $('#cancel').on("tap", function () {
                var cancelCallback = _this.settings.cancel();
                if (cancelCallback == undefined || cancelCallback) {
                    _this.close();
                }
            });

        },
        /**
         * ok
         */

        ok: function () {
            var _this = this,
                selectInfo = {};
            $('#ok').on("tap", function () {
                var selectElement = document.getElementById('selected').firstChild.firstChild;
                selectInfo.selectKey = selectElement.id;
                selectInfo.selectValue = selectElement.innerHTML;
                var okCallback = _this.settings.ok(selectInfo);
                if (okCallback == undefined || okCallback) {
                    _this.close();
                }
            });

        },


        /**
         * 设置大小
         */
        size: function () {
            // wrap.width(content.width());
        },

        /**
         * 设置位置
         */
        position: function () {

        },

        /**
         * 关闭方法
         */
        close: function () {
            $('#selectModule').remove();
        }

    };

    /**
     * 默认配置
     */
    SelectModule.defaults = {

        // 内容
        content: '加载中...',

        // 标题
        title: 'load',

        // 宽度
        width: 'auto',

        // 高度
        height: 'auto',

        // 取消按钮回调函数
        cancel: null,

        // 确定按钮回调函数
        ok: null,

        // z-index值
        zIndex: 9999

    };

    var selectModule = function (options) {
        return new SelectModule(options);
    };


    window.selectModule = $.selectModule = $.selectModule = selectModule;

})(window.jQuery, window);


var setPage = function (pageCount, pageNumber, totalCount) {
    var str = "";
    if (pageCount || pageCount > 0) {
        str = '<ul style="clear: both;height: 30px; border-left: 1px solid #f1f1f1;    font-size: 12px;" class="">' +
            '<li style="width: 60px;height: 30px; line-height: 10px;">共' + totalCount + '条</li>' +
            '<li style="width: 150px;height: 30px; line-height: 10px;border-right: 0px;">当前页/总页：' + pageNumber + '/' + pageCount + '</li>' +
            '<li class="nav_first" style="width: 40px;height: 30px; line-height: 10px;">' +
            '<a href="#" aria-label="Previous">上一页' +
            '</a></li>';
        if (pageCount >= 1) {
            var start = 1;
            var end = 5;
            if (pageCount > 5 && pageNumber > (pageCount / 2)) {
                end = pageNumber + 2;
                if (end > pageCount) end = pageCount;
                start = end - 4;
            }
            if (end > pageCount) {
                if (end > pageCount) end = pageCount;
            }
            for (var i = start; i <= end; i++) {
                if (i == pageNumber) {
                    str += '<li style="width: 30px;height: 30px; line-height: 10px;" class="active"><a href="#">' + i + '</a></li>';
                } else {
                    str += '<li style="width: 30px;height: 30px; line-height: 10px;"><a href="#">' + i + '</a></li>';
                }
            }
        }
        str += '<li pageCount="' + pageCount + '" pageNumber="' + pageNumber + '" totalCount="' + totalCount + '" ' + (pageNumber == pageCount ? "class='disabled'" : "") + ' style="width: 40px;height: 30px; line-height: 30px;"> <a href="#" aria-label="Next">下一页</a></li>' +
            '</ul>';
        str += '<span style="width:50px;height: 30px;line-height: 10px;border-right: 0px;background-color: white;position: relative;top: -10px;">' +
            '<input class="input-small" style="border-radius: 0px;border-left: 0px;padding:0px 8px;width: 40px;text-align: center;" placeholder="go" value="' + pageNumber + '"  />' +
            '<button style="width: 30px;height: 30px;background-color: #F1F1F1;border: 0px;" pageCount="' + pageCount + '" pageNumber="' + pageNumber + '" totalCount="' + totalCount + '" class="goPage">go</button></span>';
    }

    $(".content_list").on("click", ".goPage", function () {
        var page = $(this).prev().val();
        if (!isNaN(page)) {
            var pageCount = $(this).attr("pageCount");
            console.log("-->" + page + "  " + pageCount + "  " + (page > pageCount));
            if (parseInt(page) > parseInt(pageCount) || parseInt(page) < 1) {
                $.defaultDialog("请输入1~" + pageCount + "之间页数", 2000, function () {
                    $(this).prev().val($(this).attr("pagenumber"));
                });
                return false;
            }
            goPage(page);
        } else {
            $.defaultDialog("请输入数字", 2000, function () {
                $(this).prev().val($(this).attr("pageNumber"));
            });
        }
    });

    return str;
}

